package com.onenine.app.view.dialog;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.onenine.app.R;

/**
 * 加载对话框
 */
public class ListItemDialog extends AppCompatDialog {

    private Context mContext;
    private LinearLayout mContainLayout;
    private ObjectItem[] mObjectItems;
    private OnItemClickListener mItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(ObjectItem objectItem);
    }

    public static final class ObjectItem {
        public String id;
        public String name;
        public int tagInt;

        public ObjectItem() {
        }

        public ObjectItem(String id, String name) {
            this.id = id;
            this.name = name;
        }

        public ObjectItem(String id, String name, int tagInt) {
            this.id = id;
            this.name = name;
            this.tagInt = tagInt;
        }
    }

    public ListItemDialog(Context context, OnItemClickListener itemClickListener, ObjectItem... objectItems) {
        super(context, R.style.DialogStyle);
        mContext = context;
        mItemClickListener = itemClickListener;
        mObjectItems = objectItems;
        initialize();
        bindDataView();
    }

    /**
     * 初始化
     */
    private void initialize() {
        setCancelable(true);
        setCanceledOnTouchOutside(true);
        View contentView = LayoutInflater.from(mContext)
                .inflate(R.layout.dialog_list_view, null, false);
        setContentView(contentView);
        mContainLayout = contentView.findViewById(R.id.ll_list_layout);
    }

    private void bindDataView() {
        if (mObjectItems == null || mObjectItems.length == 0) {
            return;
        }
        for (final ObjectItem item : mObjectItems) {
            View itemView = LayoutInflater.from(mContext)
                    .inflate(R.layout.layout_list_item, null, false);
            TextView tvItem = itemView.findViewById(R.id.tv_title);
            tvItem.setText(item.name);
            mContainLayout.addView(itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                    if (mItemClickListener != null) {
                        mItemClickListener.onItemClick(item);
                    }
                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
